<?php
@session_start();
include_once("../initial.php");
$DOCUMENT_ROOT=$_SERVER["DOCUMENT_ROOT"];
include_once(constant('PROJECT_DIR')."/logic/deviceLogic.php");
include_once(constant('PROJECT_DIR')."/logic/courseLogic.php");
$UPLOAD_FILE_DIR=constant('PROJECT_UPLOAD_FILE');
$LIST_NUMBER_PER_PAGE=10;
require_once(constant('PROJECT_DIR')."/checkLogin.php");
require_once(constant('PROJECT_DIR')."/checkAdminLogin.php");
$adminId=$_SESSION['user'];
//logic
$action="";
if(isset($_POST['action']))
{
     $action = $_POST['action'];
}
else if(isset($_GET['action']))
{
     $action=$_GET['action'];
}
//write device
$dh = new deviceLogic();
$errorInfo="";
$deviceSearchResult=array();
$deviceSearchNote="";
switch($action)
{
     case "adddevice":
         $devInfo=array();
         $devInfo['barcode']=$_POST['barcode'];
         $devInfo['name']=$_POST['name'];
         $devInfo['type']=$_POST['type'];
         $devInfo['maintenance']=$_POST['maintenance'];
         $devInfo['info']=$_POST['info'];
         if($dh->get_device_num(array("barcode"=>$_POST['barcode']))>0)
         {
             $errorInfo="插入失败：该设备".$devInfo['barcode']."已经存在。";
             break;
         }
         else
         {
             $dh->insert_device($devInfo);
         }
         break;
    case "modifydevice":
    		$did=$_POST['deviceid'];
    		$name=$_POST['name'];
    		$type=$_POST['type'];
    		$info=$_POST['info'];
    		$mt=$_POST['maintenance'];
    		if($name!='')
    		{
    				$array=array("name"=>$name, "type"=>$type, "info"=>$info, "maintenance"=>$mt);
    				$dh->update_device($array, $did);
    		}
    		break;
    case "deletedevice":
        $delDevices=$_POST['devices'];
        foreach($delDevices as $did)
        {
            $dh->delete_device($did);
        }
        break;
    case "addDeviceCourse":
    		if(!isset($_POST['courseid']))
    		{
    				break;
    		}
    		$deviceId=$_POST['deviceid'];
    		$courseId=$_POST['courseid'];
    		$createtime=date("Y-m-d H:i:s");
    		if($deviceId!='' && $courseId!='')
    		{
    			$dh->insert_device_course($deviceId, $courseId);
    		}
    		break;
    case "removedevicecourse":
    		$deviceId=$_GET['id'];
    		$courseId=$_GET['courseid'];
    		if($deviceId!='' && $courseId!='')
    		{
    				$dh->delete_device_course($deviceId, $courseId);
    		}
    		break;
    case "upload":
    		//上传图片
    		$uploadFileNotice="";
    		$deviceId=$_POST['id'];
    		$pictureDesc=$_POST['pictureDescription'];
		    if (($_FILES['picture']['type'] == 'image/jpeg')|| ($_FILES['picture']['type'] == 'image/pjpeg')){
		    //注释：对于 IE，识别 jpg 文件的类型必须是 pjpeg，对于 FireFox，必须是 jpeg。
				    if ($_FILES['picture']['error'] > 0){
				        $uploadFileNotice='上传出错: ' . $_FILES['picture']['error'];
				    }else{
				        $uploadFileNotice= '本地文件名（你电脑上的文件名称）: ' . $_FILES['picture']['name'];
				       	$uploadFileNotice= '文件类型: ' . $_FILES['picture']['type'];
				        $uploadFileNotice= '文件长度: ' . ($_FILES['picture']['size'] / 1024) . ' Kb<br>';
				        $uploadFileNotice= '临时文件名（上传成功后保存于服务器临时文件夹中）: ' . $_FILES['picture']['tmp_name'];
				        if (file_exists($UPLOAD_FILE_DIR."/".$_FILES['picture']['name'])){
				            $uploadFileNotice= $_FILES['picture']['name'] . '重复，请重新上传';
				        }else{
				        		$extendNameIndex=strrpos($_FILES['picture']['name'], '.');
				        		$fileName=date("YmdHis").microtime().substr($_FILES['picture']['name'],$extendNameIndex);
				        		//把文件名更新到数据库
				        		$dh->insert_device_picture($deviceId, $fileName, $pictureDesc);
				            move_uploaded_file($_FILES['picture']['tmp_name'],"$UPLOAD_FILE_DIR/" . $fileName);//$_FILES['picture']['name']);
				            $uploadFileNotice= "上传成功";
				            //注释：把文件保存到了名为 $UPLOAD_FILE_DIR 的新文件夹。
				        }
		    }
				}else{
						//date("Y-m-d H:i:s");
				    $uploadFileNotice=  '你上传的文件格式不对';
				}
				$smarty->assign("uploadFileNotice", $uploadFileNotice);
    		break;
    case "searchDevice":
				$keyword = $_GET['keyword'];
    		if(strlen($keyword)<3)
    		{
    				$deviceSearchNote .="输入的关键词太短，不进行搜索,请输入长度超过3的字符串.";
    				$smarty->assign("searchNote", $deviceSearchNote);
    		}
    		//keyword长度要超过2
    		$deviceSearchResult = $dh->searchDevice($keyword, "limit 0,30");//默认显示
    		if(count($deviceSearchResult)==30)
    		{
    				$deviceSearchNote .="搜索词得到太多结果，只显示30条，请输入更长的搜索词";
    				$smarty->assign("searchNote", $deviceSearchNote);
    		}
    		if(count($deviceSearchResult)==0)
    		{
    				$deviceSearchNote .="没有结果，展示所有结果";
    				$smarty->assign("searchNote", $deviceSearchNote);
    		}
    		
    		$smarty->assign("keyword", $keyword);
    		break;
    case "modifyPicture":
    		$pid=$_POST['pid'];
    		$note=$_POST['note'];
    		$dh->update_device_picture('', $note, $pid);
    		break;
    case "removePicture":
    		$pid=$_GET['pid'];
    		$dh->remove_device_picture($pid);
    		break;
}
//read devices info
if(isset($_GET['id']))
{
     //get the editting user info
     $editDevice = $dh->get_device(array("id"=>$_GET["id"]));
     $itsCategories=$dh->get_categories($editDevice[0]['id']);
     $cnames = array();
     for($i=0; $i<count($itsCategories); $i++)
     {
     		array_push($cnames, $itsCategories[$i]['name']);
     }
     $editDevice[0]['categories']=join(',', $cnames);
     $smarty->assign("editDevice", $editDevice[0]);
     
     //读取图片展示信息
     $pictures=$dh->get_device_pictures($_GET["id"]);
     for($i=0; $i<count($pictures); $i++)
     {
     		$pictures[$i]['pictureUrl']=constant('PROJECT_URL')."/".constant('PICTURE_SUBDIR')."/".$pictures[$i]['picture_name'];
     }
     $smarty->assign("pictures", $pictures);
     
     //读取与设备相关的课程信息
     //读取所有课程
     $courseLg = new courseLogic();
     $courses= $courseLg->get_course("","order by id desc", "");
     //读取设备相关的课程
     $deviceCourses=$dh->get_device_courses($editDevice[0]['id']);
     
     //去掉设备已经选择的课程
     $filterCourses=array();
     for($i=0; $i<count($courses); $i++)
     {
     		$contains=0;
     		for($j=0; $j<count($deviceCourses); $j++)
     		{
     				if($deviceCourses[$j]['cid'] == $courses[$i]['id'])
     				{
     						$contains=1;
     						break;
     				}
     		}
     		if($contains==0)
     		{
     			array_push($filterCourses, $courses[$i]);
     		}
     	}
     	$smarty->assign("courses", $filterCourses);
     	
     $courseId2Name=array();
     if(count($deviceCourses)>0)
     {
     		for($i=0; $i< count($courses); $i++)
     		{
     				$courseId2Name[$courses[$i]['id']]=$courses[$i]['name'];
     			}
     	}
     for($i=0; $i < count($deviceCourses); $i++)
     {
     		$deviceCourses[$i]['courseName']=$courseId2Name[$deviceCourses[$i]['cid']];
     }
     if(count($deviceCourses)>0)
     {
     			$smarty->assign("deviceCourses", $deviceCourses);
     }
     	//设备与课程相关的信息结束
}

//handling the page index
$coursesNumber=0;
if(count($deviceSearchResult)>0)
{
		$devicesNumber=count($deviceSearchResult);
}
else
{
	$devicesNumber=$dh->get_device_num();
}

$pageIndex=1;
$totalPageNumber=ceil($devicesNumber/$LIST_NUMBER_PER_PAGE);
if(isset($_GET['pageIndex']))
{
     $pageIndex=$_GET['pageIndex'];
     if($pageIndex<1 || $pageIndex > $totalPageNumber)
     {
         $pageIndex=1;
     }
}
$startItem=($pageIndex-1)*$LIST_NUMBER_PER_PAGE;
$ItemNumber=$LIST_NUMBER_PER_PAGE;

$leftPageIndex=$pageIndex<=1?1:$pageIndex-1;
$rightPageIndex=$pageIndex>=$totalPageNumber?$totalPageNumber:$pageIndex+1;
$leftMostPageIndex=$pageIndex<=5?1:$pageIndex-5;//左边显示5个页面索引
$rightMostPageIndex=$totalPageNumber<$pageIndex+5?$totalPageNumber:$pageIndex+5;//右边显示5个页面索引
$smarty->assign("leftMostPageIndex",$leftMostPageIndex);
$smarty->assign("rightMostPageIndex",$rightMostPageIndex);
$smarty->assign("leftPageIndex",$leftPageIndex);
$smarty->assign("rightPageIndex",$rightPageIndex);
$smarty->assign("pageIndex",$pageIndex);
$smarty->assign("devicesNumber", $devicesNumber);
$alldevices=array();
if(count($deviceSearchResult)>0)
{
		$alldevices=$deviceSearchResult;
}
else
{
		$alldevices=$dh->get_device('',"order by id desc", "limit $startItem,$ItemNumber");
}
$smarty->assign("devices",$alldevices);
//handling page Index end

if(strlen($errorInfo)>0)
{
     $smarty->assign("insertMessage", $errorInfo);
}
$smarty->assign("menuSelected", "device");
$smarty->assign("projectUrl", constant('PROJECT_URL'));
$smarty->assign("currentUrl","admin/device.php");
$smarty->display("admin/device.html");
?>
